/// 对外部保持不可变，同时在方法内部还是可以变化  
/// testdouble  测试替代 - -模拟对象

/// mock object  功能模拟
pub trait Messager {
    fn send(&self, msg: &str);
}

pub struct LimitTracker<'a, T: 'a + Messager> {
    messager: &'a T,
    value: usize,
    max: usize,
}

impl<'a, T> LimitTracker<'a, T>
where
    T: Messager,
{
    pub fn new(messager: &T, max: usize) -> LimitTracker<T> {
        LimitTracker {
            messager,
            value: 0,
            max,
        }
    }

    pub fn set_value(&mut self, value: usize) {
        self.value = value;

        let percentage_of_max = self.value as f64 / self.max as f64;
        if percentage_of_max >= 1.0 {
            self.messager.send("over");
        } else if percentage_of_max >= 9.0 {
            self.messager.send("over 90%");
        } else if percentage_of_max >= 0.75 {
            self.messager.send("over 75%");
        }
    }
}

/// 使用RefCell<T> 在运行是记录借用信息
/// - borrow
///   - 返回智能指针Ref<T>,它实现了Deref
/// - borrow_mut
///   - 返回智能指针RefMut<T>,它实现了Deref
/// 会记录存在多少个活跃的Ref<T>和RefMut<T>
/// borrow  不可变借用计数+1
/// Ref<T>的值离开作用域被释放时：  不可变借用计数-1
/// borrow_mut  可变借用计数+1
/// RefMut<T>的值离开作用域被释放时：  可变借用计数-1


#[cfg(test)]

mod tests {
    use std::cell::RefCell;

    use super::*;

    struct MockMessenger {
        sent_messages: RefCell<Vec<String>>,
    }

    impl MockMessenger {
        fn new() -> MockMessenger {
            MockMessenger {
                sent_messages: RefCell::new(vec![]),
            }
        }
    }

    impl Messager for MockMessenger {
        fn send(&self, message: &str) {
            self.sent_messages.borrow_mut().push(String::from(message))
        }
    }

    #[test]
    fn it_sends_an_over_75_percent_warning_message() {
        let mock_message = MockMessenger::new();
        let mut limit_tracker = LimitTracker::new(&mock_message, 100);
        limit_tracker.set_value(80);
        assert_eq!(mock_message.sent_messages.borrow().len(), 1);
    }
}
